package com.example.demo.controller;

import com.example.demo.domian.CourseGrade;
import com.example.demo.domian.Student;
import com.example.demo.domian.Teacher;

import java.io.*;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;

public class TestDemo {

    private final static String filePath = "src/main/resources/";
    private final static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss");
    public static void main(String[] args) {
        System.out.println("---------------欢迎来到学生管理系统-----------------");
        while (true) {
            boolean finalFlag = true;
            System.out.println("请输入要登录的系统或使用的功能序号");
            System.out.println("1.登录学生系统             2.登陆教师系统              3.退出管理系统");
            Scanner scanner = new Scanner(System.in);
            // 输入的内容
            String next = scanner.next();
            // 登录学生系统
            if (next.contains("1")) {
                while (true) {
                    boolean flag = true;
                    System.out.println("----------------学生登陆系统-----------------------------");
                    System.out.println("1.登录       2.添加/注册学生         3.删除学生         4.查询学生        5.退出系统    ");
                    System.out.println("请输入要使用的功能序号");
                    Scanner studentScanner = new Scanner(System.in);
                    String studentValue = studentScanner.next();
                    switch (studentValue) {
                        case "1":
                            login();
                            break;
                        case "2":
                            addStudent();
                            break;
                        case "3":
                            deleteStudent();
                            break;
                        case "4":
                            selectStudent();
                            break;
                        case "5":
                            flag = false;
                            break;
                    }
                     if (!flag){
                         break;
                     }
                }
            }else if ("2".equals(next) || next.contains("2")) {
                while (true) {
                    boolean flag = true;
                    System.out.println("------------------老师登陆系统------------------------");
                    System.out.println("1.登录       2.添加/注册老师         3.删除老师          4.查询老师          5.退出系统    ");
                    System.out.println("请输入要使用的功能序号");
                    Scanner studentScanner = new Scanner(System.in);
                    String studentValue = studentScanner.next();
                    switch (studentValue) {
                        case "1":
                            loginTeacher();
                            break;
                        case "2":
                            addTeacher();
                            break;
                        case "3":
                            deleteTeacher();
                            break;
                        case "4":
                            selectTeacher();
                            break;
                        case "5":
                            flag = false;
                            break;
                    }
                    if (!flag){
                        break;
                    }
                }
            }else {
                System.out.println("退出学生管理系统成功!");
                break;
            }
            if (!finalFlag){
                break;
            }
        }
    }
    private static void selectTeacher() {
        System.out.println("请输入要查询的老师的教职号");
        Scanner scanner = new Scanner(System.in);
        String teacherNo = scanner.next();
        List<Teacher> teacherList = findAllTeacher();
        List<Teacher> list = teacherList.stream().filter(teacher-> teacher.getTeacherNo().equals(teacherNo)).collect(Collectors.toList());
        if (!list.isEmpty()) {
            System.out.println(list.get(0));
        }else {
            System.out.println("没有教职号为"+teacherNo+"的老师") ;
        }
    }
    private static void deleteTeacher() {
        System.out.println("请输入要删除的教师编号");
        Scanner scanner = new Scanner(System.in);
        String teacherNo = scanner.next();
        List<Teacher> allTeacher = findAllTeacher();
        List<Teacher> teachers = allTeacher.stream().filter(teacher -> teacher.getTeacherNo().equals(teacherNo)).collect(Collectors.toList());
        List<Teacher> teachertList = allTeacher.stream().filter(teacher -> !teacher.getTeacherNo().equals(teacherNo)).collect(Collectors.toList());
        if (!teachers.isEmpty()){
            try {
                Files.delete(Paths.get(filePath + "teacher.txt"));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            for (Teacher teacher : teachertList) {
                writeTeacher(teacher);
            }
            writeOperateTeacherTxt(teachers.get(0),null,"delete");
        }else {
            System.out.println("没有教职号为"+teacherNo+"的老师");
        }
    }

    private static void addTeacher() {
        Teacher teacher = new Teacher();
        while (true) {
            System.out.println("请输入您的教工职号(学号长度在5-10之间,纯数字)");
            Scanner noScanner = new Scanner(System.in);
            // 学号
            String teacherNo = noScanner.next();
            // 检验
            if (teacherNo.length() >= 5 && teacherNo.length() <= 10 && teacherNo.matches("[0-9]+")) {
                List<Teacher> teacherList = findAllTeacher();
                List<Teacher> collect = teacherList.stream().filter(t -> t.getTeacherNo().equals(teacherNo)).collect(Collectors.toList());
                if (collect.isEmpty()) {
                    teacher.setTeacherNo(teacherNo);
                    break;
                }
            } else {
                System.out.println("您输入的教工职号不符合要求,请重新输入");
            }
        }
        // 输入密码
        while (true) {
            System.out.println("请输入要注册的密码(密码长度在6-10之间,纯数字)");
            Scanner firstPasswordScanner = new Scanner(System.in);
            String firstPassword = firstPasswordScanner.next();
            if (firstPassword.length() >= 5 && firstPassword.length() <= 10 && firstPassword.matches("[0-9]+")) {
                while (true) {
                    System.out.println("请再次输入您的密码");
                    Scanner finalPasswordScanner = new Scanner(System.in);
                    String finalPassword = finalPasswordScanner.next();
                    if (finalPassword.length() >= 5 && finalPassword.length() <= 10 && finalPassword.matches("[0-9]+")) {
                        if (firstPassword.equals(finalPassword)) {
                            System.out.println("两次密码一致，设置成功!");
                            break;
                        } else {
                            System.out.println("两次密码不一致,请重新输入");
                        }
                    }
                }
                break;
            } else {
                System.out.println("密码不符合要求,请重新输入");
            }
        }
        System.out.println("请输入您的姓名");
        Scanner nameScanner = new Scanner(System.in);
        String name = nameScanner.next();
        teacher.setName(name);

        System.out.println("请输入您的年龄");
        Scanner ageScanner = new Scanner(System.in);
        String age = ageScanner.next();
        teacher.setAge(age);

        System.out.println("请输入您的性别");
        Scanner sexScanner = new Scanner(System.in);
        String sex = sexScanner.next();
        teacher.setSex(sex);

        System.out.println("请输入您在的学院");
        Scanner schoolScanner = new Scanner(System.in);
        String school = schoolScanner.next();
        teacher.setSchool(school);

        System.out.println("请输入您教的班级(目前只有大数据一班、大数据二班)");
        Scanner classScanner = new Scanner(System.in);
        String classStudent = classScanner.next();
        teacher.setTeacherClass(classStudent);
        System.out.println("请输入您教学的科目:1.数学  2.英语  3.体育(请输入教学科目序号)");
        Scanner subjectScanner = new Scanner(System.in);
        String subject = subjectScanner.next();
        switch (subject) {
            case "1":
                teacher.setSubject("数学");
                break;
            case "2":
                teacher.setSubject("英语");
                break;
            case "3":
                teacher.setSubject("体育");
                break;
        }
        writeTeacher(teacher);
        writeOperateTeacherTxt(teacher, null,"add");
        System.out.println("添加或注册成功！");
    }
    private static void loginTeacher() {
        List<Teacher> collect;
        List<Teacher> allTeacher;
        while (true) {
            System.out.println("请输入教职编号");
            Scanner scanner = new Scanner(System.in);
            String next = scanner.next();
            allTeacher= findAllTeacher();
            collect = allTeacher.stream().filter(teacher -> teacher.getTeacherNo().equals(next)).collect(Collectors.toList());
            if (collect.isEmpty()) {
                System.out.println("没有该老师");

            } else {
                while (true) {
                    System.out.println("请输入密码,默认密码000000");
                    Scanner password = new Scanner(System.in);
                    String passwordValue = password.next();
                    if (!"000000".equals(passwordValue)) {
                        System.out.println("密码输入错误");
                    } else {
                        break;
                    }
                }
                break;
            }
        }
        System.out.println("登录成功，可以开始使用老师系统");
        System.out.println("--------------欢迎进入老师系统----------------");
        getTeacherInfo(collect.get(0), allTeacher);
    }
    private static void selectStudent() {
        System.out.println("请输入要查询的学生学号");
        Scanner scanner = new Scanner(System.in);
        String studentNo = scanner.next();
        List<Student> studentList = findAllStudent();
        List<Student> list = studentList.stream().filter(student -> student.getStudentNo().equals(studentNo)).collect(Collectors.toList());
        if (!list.isEmpty()) {
            System.out.println(list.get(0));
        }else {
            System.out.println("没有学号为"+studentNo+"的学生") ;
        }
    }
    private static void deleteStudent() {
        System.out.println("请输入要删除的学生学号");
        Scanner scanner = new Scanner(System.in);
        String studentNo = scanner.next();
        List<Student> allStudent = findAllStudent();
        List<Student> students = allStudent.stream().filter(student -> student.getStudentNo().equals(studentNo)).collect(Collectors.toList());
        List<Student> studentList = allStudent.stream().filter(student -> !student.getStudentNo().equals(studentNo)).collect(Collectors.toList());
        if (!students.isEmpty()){
            try {
                Files.delete(Paths.get(filePath + "student-大数据一班.txt"));
                Files.delete(Paths.get(filePath + "student-大数据二班.txt"));
                writeOperateStudentTxt(students.get(0),null,"delete");
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            for (Student student : studentList) {
                write(student);
            }
        }else {
            System.out.println("没有学号为"+studentNo+"的学生");
        }
    }
    private static void addStudent() {
        Student student = new Student();
        while (true) {
            System.out.println("请输入学生学号(学号长度在5-10之间,纯数字)");
            Scanner noScanner = new Scanner(System.in);
            // 学号
            String studentNo = noScanner.next();
            // 检验
            if (studentNo.length() >= 5 && studentNo.length() <= 10 && studentNo.matches("[0-9]+")) {
                List<Student> studentList = findAllStudent();
                List<Student> collect = studentList.stream().filter(s -> s.getStudentNo().equals(studentNo)).collect(Collectors.toList());
                if (collect.isEmpty()) {
                    student.setStudentNo(studentNo);
                    break;
                }
            } else {
                System.out.println("学号不符合要求,请重新输入");
            }
        }
        // 输入密码
        while (true) {
            System.out.println("请输入学生密码(密码长度在6-10之间,纯数字)");
            Scanner firstPasswordScanner = new Scanner(System.in);
            String firstPassword = firstPasswordScanner.next();
            if (firstPassword.length() >= 5 && firstPassword.length() <= 10 && firstPassword.matches("[0-9]+")) {
                while (true) {
                    System.out.println("请再次输入学生密码");
                    Scanner finalPasswordScanner = new Scanner(System.in);
                    String finalPassword = finalPasswordScanner.next();
                    if (finalPassword.length() >= 5 && finalPassword.length() <= 10 && finalPassword.matches("[0-9]+")) {
                        if (firstPassword.equals(finalPassword)) {
                            System.out.println("两次密码一致，设置成功!");
                            break;
                        } else {
                            System.out.println("两次密码不一致,请重新输入");
                        }
                    }
                }
                break;
            } else {
                System.out.println("密码不符合要求,请重新输入");
            }
        }
        System.out.println("请输入学生的姓名");
        Scanner nameScanner = new Scanner(System.in);
        String name = nameScanner.next();
        student.setName(name);

        System.out.println("请输入学生的年龄");
        Scanner ageScanner = new Scanner(System.in);
        String age = ageScanner.next();
        student.setAge(age);

        System.out.println("请输入学生的性别");
        Scanner sexScanner = new Scanner(System.in);
        String sex = sexScanner.next();
        student.setSex(sex);

        System.out.println("请输入学生的学院");
        Scanner schoolScanner = new Scanner(System.in);
        String school = schoolScanner.next();
        student.setSchool(school);

        System.out.println("请输入学生的班级,目前只有大数据一班、大数据二班");
        Scanner classScanner = new Scanner(System.in);
        String classStudent = classScanner.next();
        student.setStudentClass(classStudent);

        CourseGrade courseGrade = new CourseGrade();
        courseGrade.setStudentNo(student.getStudentNo());
        courseGrade.setMath(String.valueOf((int)(Math.random() * 101)));
        courseGrade.setEnglish(String.valueOf((int)(Math.random() * 101)));
        courseGrade.setSports(String.valueOf((int)(Math.random() * 101)));
        writeCourseGrade(courseGrade);
        write(student);
        writeOperateStudentTxt(student, null,"add");
        System.out.println("添加或注册成功！");
    }
    public static void write(Student student) {
        String finalFilePath;
        if (student.getStudentClass().equals("大数据一班")) {
            finalFilePath = filePath + "student-大数据一班.txt";
        } else {
            finalFilePath = filePath + "student-大数据二班.txt";
        }
        try (FileWriter fw = new FileWriter(finalFilePath, true); // 第二个参数为true表示追加模式
             BufferedWriter bw = new BufferedWriter(fw)) {
             String anewline = System.lineSeparator();
            bw.write( student + anewline);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void writeCourseGrade(CourseGrade courseGrade) {
        String finalFilePath = filePath + "course-grade.txt";
        exsitFile(finalFilePath);
        try (FileWriter fw = new FileWriter(finalFilePath, true); // 第二个参数为true表示追加模式
             BufferedWriter bw = new BufferedWriter(fw)) {
            String anewline = System.lineSeparator();
            bw.write( courseGrade + anewline);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void writeTeacher(Teacher teacher) {
        String finalFilePath = filePath + "teacher.txt";
        try (FileWriter fw = new FileWriter(finalFilePath, true); // 第二个参数为true表示追加模式
             BufferedWriter bw = new BufferedWriter(fw)) {
            String anewline = System.lineSeparator();
            bw.write( teacher + anewline);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



    public static void writeOperateStudentTxt(Student student,Student newStudent,String type)  {
        String finalFilePath;
        if ("大数据一班".equals(student.getStudentClass())) {
            finalFilePath = filePath + "student-大数据一班-%s.txt";
        } else {
            finalFilePath = filePath + "student-大数据二班-%s.txt";
        }
        finalFilePath = String.format(finalFilePath,type);
        exsitFile(finalFilePath);
        try (FileWriter fw = new FileWriter(finalFilePath, true); // 第二个参数为true表示追加模式
             BufferedWriter bw = new BufferedWriter(fw)) {
            String anewline = System.lineSeparator();
            LocalDateTime now = LocalDateTime.now();
            String format = now.format(formatter);
            String operateType = "";
            if ("add".equals(type)){
              operateType = "添加";
            }else if ("delete".equals(type)){
              operateType = "删除";
            }else if ("update".equals(type)){
               operateType= "修改";
                bw.write( "在" + format + operateType + "了如下内容:" + anewline);
                bw.write( "修改前："  + student + anewline);
                bw.write( "修改后："  + newStudent + anewline);
                return;
            }
            bw.write( "在" + format + operateType + "了学生：" + student + anewline);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void writeOperateTeacherTxt(Teacher teacher,Teacher newTeacher,String type)  {
        String finalFilePath = filePath + "teacher-%s.txt";
        finalFilePath = String.format(finalFilePath,type);
        exsitFile(finalFilePath);
        try (FileWriter fw = new FileWriter(finalFilePath, true); // 第二个参数为true表示追加模式
             BufferedWriter bw = new BufferedWriter(fw)) {
            String anewline = System.lineSeparator();
            LocalDateTime now = LocalDateTime.now();
            String format = now.format(formatter);
            String operateType = "";
            if ("add".equals(type)){
                operateType = "添加";
            }else if ("delete".equals(type)){
                operateType = "删除";
            }else if ("update".equals(type)){
                operateType= "修改";
                bw.write( "在" + format + operateType + "了如下内容:" + anewline);
                bw.write( "修改前："  + teacher + anewline);
                bw.write( "修改后："  + newTeacher + anewline);
                return;
            }
            bw.write( "在" + format + operateType + "了老师：" + teacher + anewline);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    private static void login() {
        List<Student> collect;
        List<Student> allStudent;
        while (true) {
            System.out.println("请输入学号");
            Scanner scanner = new Scanner(System.in);
            String next = scanner.next();
            allStudent = findAllStudent();
            collect = allStudent.stream().filter(student -> student.getStudentNo().equals(next)).collect(Collectors.toList());
            if (collect.isEmpty()) {
                System.out.println("没有该学生");
            } else {
                while (true) {
                    System.out.println("请输入密码,默认密码000000");
                    Scanner password = new Scanner(System.in);
                    String passwordValue = password.next();
                    if (!"000000".equals(passwordValue)) {
                        System.out.println("密码输入错误");
                    } else {
                        break;
                    }
                }
                break;
            }
        }
        System.out.println("登录成功，可以开始使用学生系统");
        System.out.println("--------------欢迎进入学生系统----------------");
        getUserInfo(collect.get(0), allStudent);
    }

    private static void getUserInfo(Student student,List<Student> studentList)  {
        while (true) {
            boolean flag = true;
            System.out.println("1.修改个人信息  2.修改个人密码  3.查看全部成绩  4.查看单科成绩  5.退出学生系统");
            System.out.println("请输入你要使用的的功能序号:");
            Scanner scanner = new Scanner(System.in);
            String next = scanner.next();
            List<CourseGrade> gradeList = findAllStudentGrade().stream().filter(g -> g.getStudentNo().equals(student.getStudentNo())).collect(Collectors.toList());
            List<Student> students = studentList.stream().filter(studentInfo -> studentInfo.getStudentNo().equals(student.getStudentNo())).collect(Collectors.toList());
            Student newStudent = students.get(0);
            Student oldStudent = new Student();
            oldStudent.setStudentNo(student.getStudentNo());
            oldStudent.setName(student.getName());
            oldStudent.setAge(student.getAge());
            oldStudent.setSex(student.getSex());
            oldStudent.setSchool(student.getSchool());
            oldStudent.setStudentClass(student.getStudentClass());
            switch (next) {
                case "1":
                    System.out.println("你的信息为:" + student);
                    while (true) {
                        try {
                            Files.delete(Paths.get(filePath + "student-大数据一班.txt"));
                            Files.delete(Paths.get(filePath + "student-大数据二班.txt"));
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                        boolean flag1 = true;
                        System.out.println("请输入您要修改的信息的序号");
                        System.out.println("1.姓名  2.性别  3.年龄  4.学院  5.班级  6.退出");
                        Scanner selectScanner = new Scanner(System.in);
                        String no = selectScanner.next();
                        switch (no){
                            case "1" :
                                System.out.println("请输入你的姓名");
                                Scanner nameScanner = new Scanner(System.in);
                                String name = nameScanner.next();
                                newStudent.setName(name);
                                System.out.println("修改成功");
                                System.out.println("你的信息为:" + newStudent);

                                writeOperateStudentTxt(oldStudent,newStudent,"update");
                                for (Student studentInfo : studentList) {
                                    write(studentInfo);
                                }
                                break;
                            case "2" :
                                System.out.println("请输入你的年龄");
                                Scanner ageScanner = new Scanner(System.in);
                                String age = ageScanner.next();
                                student.setAge(age);
                                System.out.println("修改成功");
                                System.out.println("你的信息为:" + student);
                                newStudent.setAge(age);
                                writeOperateStudentTxt(oldStudent,newStudent,"update");
                                studentList.forEach(TestDemo::write);
                                break;
                            case "3" :
                                System.out.println("请输入你的性别");
                                Scanner sexScanner = new Scanner(System.in);
                                String sex = sexScanner.next();
                                System.out.println("修改成功");
                                System.out.println("你的信息为:" + student);
                                newStudent.setSex(sex);
                                writeOperateStudentTxt(oldStudent,newStudent,"update");
                                studentList.forEach(TestDemo::write);
                                break;
                            case "4" :
                                System.out.println("请输入你的学院");
                                Scanner schoolScanner = new Scanner(System.in);
                                String school = schoolScanner.next();
                                System.out.println("修改成功");
                                System.out.println("你的信息为:" + student);
                                newStudent.setSchool(school);
                                writeOperateStudentTxt(oldStudent,newStudent,"update");
                                studentList.forEach(TestDemo::write);
                                break;
                            case "5" :
                                System.out.println("请输入你的班级");
                                Scanner classScanner = new Scanner(System.in);
                                String classStudent = classScanner.next();
                                System.out.println("修改成功");
                                System.out.println("你的信息为:" + student);
                                newStudent.setStudentClass(classStudent);
                                writeOperateStudentTxt(oldStudent,newStudent,"update");
                                studentList.forEach(TestDemo::write);
                                break;
                            case "6" :
                                flag1 = false;
                                System.out.println("退出成功");
                        }
                        if (!flag1){
                            break;
                        }
                    }
                case "2" :
                    System.out.println("暂不支持");
                    break;
                case "3" :
                    if (gradeList.isEmpty()){
                        System.out.println("您的成绩未录入,请稍后查询");
                    }else {
                        CourseGrade courseGrade = gradeList.get(0);
                        System.out.println("您的成绩为: " + courseGrade);
                    }
                    break;
                case "4" :
                    getUserGrade(student,gradeList);
                    break;
                case "5" :
                    flag =false;
                    break;
            }
            if (!flag){
                break;
            }
        }
    }

    private static void getTeacherInfo(Teacher teacher,List<Teacher> teacherList)  {
        while (true) {
            boolean flag = true;
            System.out.println("1.修改个人信息  2.修改个人密码  3.修改学生成绩  4.查询教学班所有学生成绩  5.教学班级学生成绩(高到低)  6.教学班成绩最高分   7.教学班成绩最低分   8.教学班成绩平均分   9.退出老师系统");
            System.out.println("请输入你要使用的的功能序号:");
            Scanner scanner = new Scanner(System.in);
            String next = scanner.next();
            List<Teacher> teachers = teacherList.stream().filter(teacherInfo -> teacherInfo.getTeacherNo().equals(teacher.getTeacherNo())).collect(Collectors.toList());
            Teacher newTeacher = teachers.get(0);
            Teacher oldTeacher = new Teacher();
            oldTeacher.setTeacherNo(teacher.getTeacherNo());
            oldTeacher.setName(teacher.getName());
            oldTeacher.setAge(teacher.getAge());
            oldTeacher.setSex(teacher.getSex());
            oldTeacher.setSchool(teacher.getSchool());
            oldTeacher.setTeacherClass(teacher.getTeacherClass());
            oldTeacher.setSubject(teacher.getSubject());
            switch (next) {
                case "1":
                    System.out.println("你的信息为:" + teacher);
                    while (true) {
                        try {
                            Files.delete(Paths.get(filePath + "teacher.txt"));
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                        boolean flag1 = true;
                        System.out.println("请输入您要修改的信息的序号");
                        System.out.println("1.姓名  2.性别  3.年龄  4.学院  5.班级  6.教学科目  7.退出");
                        Scanner selectScanner = new Scanner(System.in);
                        String no = selectScanner.next();
                        switch (no){
                            case "1" :
                                System.out.println("请输入你的姓名");
                                Scanner nameScanner = new Scanner(System.in);
                                String name = nameScanner.next();
                                newTeacher.setName(name);
                                System.out.println("修改成功");
                                System.out.println("你的信息为:" + newTeacher);
                                writeOperateTeacherTxt(oldTeacher,newTeacher,"update");
                                for (Teacher teacherInfo : teacherList) {
                                    writeTeacher(teacherInfo);
                                }
                                break;
                            case "2" :
                                System.out.println("请输入你的年龄");
                                Scanner ageScanner = new Scanner(System.in);
                                String age = ageScanner.next();
                                newTeacher.setAge(age);
                                System.out.println("修改成功");
                                System.out.println("你的信息为:" + newTeacher);
                                newTeacher.setAge(age);
                                writeOperateTeacherTxt(oldTeacher,newTeacher,"update");
                                teacherList.forEach(TestDemo::writeTeacher);
                                break;
                            case "3" :
                                System.out.println("请输入你的性别");
                                Scanner sexScanner = new Scanner(System.in);
                                String sex = sexScanner.next();
                                System.out.println("修改成功");
                                System.out.println("你的信息为:" + newTeacher);
                                newTeacher.setSex(sex);
                                writeOperateTeacherTxt(oldTeacher,newTeacher,"update");
                                teacherList.forEach(TestDemo::writeTeacher);
                                break;
                            case "4" :
                                System.out.println("请输入你的学院");
                                Scanner schoolScanner = new Scanner(System.in);
                                String school = schoolScanner.next();
                                System.out.println("修改成功");
                                System.out.println("你的信息为:" + newTeacher);
                                newTeacher.setSchool(school);
                                writeOperateTeacherTxt(oldTeacher,newTeacher,"update");
                                teacherList.forEach(TestDemo::writeTeacher);
                                break;
                            case "5" :
                                System.out.println("请输入你的班级");
                                Scanner classScanner = new Scanner(System.in);
                                String classStudent = classScanner.next();
                                System.out.println("修改成功");
                                System.out.println("你的信息为:" + newTeacher);
                                newTeacher.setTeacherClass(classStudent);
                                writeOperateTeacherTxt(oldTeacher,newTeacher,"update");
                                teacherList.forEach(TestDemo::writeTeacher);
                                break;
                            case "6" :
                                System.out.println("请输入你的教学科目");
                                Scanner subjectScanner = new Scanner(System.in);
                                String subject = subjectScanner.next();
                                newTeacher.setSubject(subject);
                                System.out.println("修改成功");
                                System.out.println("你的信息为:" + newTeacher);
                                writeOperateTeacherTxt(oldTeacher,newTeacher,"update");
                                teacherList.forEach(TestDemo::writeTeacher);
                                break;
                            case "7" :
                                flag1 = false;
                                System.out.println("退出成功");
                                break;
                        }
                        if (!flag1){
                            break;
                        }
                    }
                case "2" :
                    System.out.println("暂不支持");
                    break;
                case "3" :
                    updateStudentInfo(newTeacher);
                    break;
                case "4" :
                    selectStudentGrade(newTeacher);
                    break;
                case "5" :
                    selectStudentGradeSort(newTeacher);
                    break;
                case "6" :
                    selectStudentGradeMax(newTeacher);
                    break;
                case "7" :
                    selectStudentGradeMin(newTeacher);
                    break;
                case "8" :
                    selectStudentGradeAvg(newTeacher);
                    break;
                case "9" :
                    flag =false;
                    break;
            }
            if (!flag){
                break;
            }

        }
    }
    private static void selectStudentGradeAvg(Teacher newTeacher) {
        List<Student> studentList = findAllStudent();
        List<CourseGrade> gradeList = findAllStudentGrade();
        List<CourseGrade> newList = new ArrayList<>();
        List<Student> list = studentList.stream().filter(student ->  student.getStudentClass().equals(newTeacher.getTeacherClass())).collect(Collectors.toList());
        if (list.isEmpty()){
            System.out.println("该班级没有学生");
            return;
        }
        list.forEach(student -> {
            List<CourseGrade> courseGradeList = gradeList.stream().filter(courseGrade -> courseGrade.getStudentNo().equals(student.getStudentNo())).collect(Collectors.toList());
            newList.addAll(courseGradeList);
        });
        BigDecimal avg = getBigDecimal(newTeacher, newList, list);
        System.out.println("该班级"+newTeacher.getSubject()+"成绩平均分:"+avg);
    }

    private static BigDecimal getBigDecimal(Teacher newTeacher, List<CourseGrade> newList, List<Student> list) {
        BigDecimal sumGrade = new BigDecimal(0);
        for (CourseGrade courseGrade : newList) {
            if ("数学".equals(newTeacher.getSubject())){
                sumGrade = sumGrade.add(new BigDecimal(courseGrade.getMath()));
            }else if ("英语".equals(newTeacher.getSubject())){
                sumGrade = sumGrade.add(new BigDecimal(courseGrade.getEnglish()));
            }else {
                sumGrade = sumGrade.add(new BigDecimal(courseGrade.getSports()));
            }
        }
        BigDecimal avg = sumGrade.divide(BigDecimal.valueOf(list.size())).setScale(2, BigDecimal.ROUND_HALF_UP);
        return avg;
    }
    private static void selectStudentGradeMin(Teacher newTeacher) {
        List<Student> studentList = findAllStudent();
        List<CourseGrade> gradeList = findAllStudentGrade();
        List<Student> list = studentList.stream().filter(student ->  student.getStudentClass().equals(newTeacher.getTeacherClass())).collect(Collectors.toList());
        if (list.isEmpty()){
            System.out.println("你班级还没录入学生信息");
        }else {
            if ("数学".equals(newTeacher.getSubject())){
                gradeList=gradeList.stream().sorted(Comparator.comparing(CourseGrade::getMath)).collect(Collectors.toList());
                String math = gradeList.get(0).getMath();
                List<CourseGrade> courseGradeList = gradeList.stream().filter(courseGrade -> courseGrade.getMath().equals(math)).collect(Collectors.toList());
                courseGradeList.forEach(courseGrade -> {
                    String studentNo = courseGrade.getStudentNo();
                    List<Student> collect = list.stream().filter(student -> student.getStudentNo().equals(studentNo)).collect(Collectors.toList());
                    if (!collect.isEmpty()){
                        System.out.println(collect.get(0) + "\t\t"+ "数学成绩=" + courseGrade.getMath());
                    }
                });
            }else if ("英语".equals(newTeacher.getSubject())){
                gradeList=gradeList.stream().sorted(Comparator.comparing(CourseGrade::getEnglish)).collect(Collectors.toList());
                String english= gradeList.get(0).getEnglish();
                List<CourseGrade> courseGradeList = gradeList.stream().filter(courseGrade -> courseGrade.getEnglish().equals(english)).collect(Collectors.toList());
                courseGradeList.forEach(courseGrade -> {
                    String studentNo = courseGrade.getStudentNo();
                    List<Student> collect = list.stream().filter(student -> student.getStudentNo().equals(studentNo)).collect(Collectors.toList());
                    if (!collect.isEmpty()){
                        System.out.println(collect.get(0) + "\t\t"+ "英语成绩=" + courseGrade.getEnglish());
                    }
                });
            }else {
                gradeList=gradeList.stream().sorted(Comparator.comparing(CourseGrade::getSports)).collect(Collectors.toList());
                String sports= gradeList.get(0).getSports();
                List<CourseGrade> courseGradeList = gradeList.stream().filter(courseGrade -> courseGrade.getSports().equals(sports)).collect(Collectors.toList());
                courseGradeList .forEach(courseGrade -> {
                    String studentNo = courseGrade.getStudentNo();
                    List<Student> collect = list.stream().filter(student -> student.getStudentNo().equals(studentNo)).collect(Collectors.toList());
                    if (!collect.isEmpty()){
                        System.out.println(collect.get(0) +"\t\t"+ "体育成绩=" + courseGrade.getSports());
                    }
                });
            }
        }
    }
    private static void selectStudentGradeMax(Teacher newTeacher) {
        List<Student> studentList = findAllStudent();
        List<CourseGrade> gradeList = findAllStudentGrade();
        List<Student> list = studentList.stream().filter(student ->  student.getStudentClass().equals(newTeacher.getTeacherClass())).collect(Collectors.toList());
        if (list.isEmpty()){
            System.out.println("你班级还没录入学生信息");
        }else {
            if ("数学".equals(newTeacher.getSubject())){
                gradeList=gradeList.stream().sorted(Comparator.comparing(CourseGrade::getMath).reversed()).collect(Collectors.toList());
                String math = gradeList.get(0).getMath();
                List<CourseGrade> courseGradeList = gradeList.stream().filter(courseGrade -> courseGrade.getMath().equals(math)).collect(Collectors.toList());
                courseGradeList.forEach(courseGrade -> {
                    String studentNo = courseGrade.getStudentNo();
                    List<Student> collect = list.stream().filter(student -> student.getStudentNo().equals(studentNo)).collect(Collectors.toList());
                    if (!collect.isEmpty()){
                        System.out.println(collect.get(0) + "\t\t"+ "数学成绩=" + courseGrade.getMath());
                    }
                });
            }else if ("英语".equals(newTeacher.getSubject())){
                gradeList=gradeList.stream().sorted(Comparator.comparing(CourseGrade::getEnglish).reversed()).collect(Collectors.toList());
                String english= gradeList.get(0).getEnglish();
                List<CourseGrade> courseGradeList = gradeList.stream().filter(courseGrade -> courseGrade.getEnglish().equals(english)).collect(Collectors.toList());
                courseGradeList.forEach(courseGrade -> {
                    String studentNo = courseGrade.getStudentNo();
                    List<Student> collect = list.stream().filter(student -> student.getStudentNo().equals(studentNo)).collect(Collectors.toList());
                    if (!collect.isEmpty()){
                        System.out.println(collect.get(0) + "\t\t"+ "英语成绩=" + courseGrade.getEnglish());
                    }
                });
            }else {
                gradeList=gradeList.stream().sorted(Comparator.comparing(CourseGrade::getSports).reversed()).collect(Collectors.toList());
                String sports= gradeList.get(0).getSports();
                List<CourseGrade> courseGradeList = gradeList.stream().filter(courseGrade -> courseGrade.getSports().equals(sports)).collect(Collectors.toList());
                courseGradeList .forEach(courseGrade -> {
                    String studentNo = courseGrade.getStudentNo();
                    List<Student> collect = list.stream().filter(student -> student.getStudentNo().equals(studentNo)).collect(Collectors.toList());
                    if (!collect.isEmpty()){
                        System.out.println(collect.get(0) +"\t\t"+ "体育成绩=" + courseGrade.getSports());
                    }
                });
            }
        }
    }
    private static void selectStudentGradeSort(Teacher newTeacher) {
        List<Student> studentList = findAllStudent();
        List<CourseGrade> gradeList = findAllStudentGrade();
        List<Student> list = studentList.stream().filter(student ->  student.getStudentClass().equals(newTeacher.getTeacherClass())).collect(Collectors.toList());
        if (list.isEmpty()){
            System.out.println("你班级还没录入学生信息");
        }else {
            if ("数学".equals(newTeacher.getSubject())){
                gradeList=gradeList.stream().sorted(Comparator.comparing(CourseGrade::getMath).reversed()).collect(Collectors.toList());
                gradeList.forEach(courseGrade -> {
                    String studentNo = courseGrade.getStudentNo();
                    List<Student> collect = list.stream().filter(student -> student.getStudentNo().equals(studentNo)).collect(Collectors.toList());
                    if (!collect.isEmpty()){
                        System.out.println(collect.get(0) + "\t\t"+ "数学成绩=" + courseGrade.getMath());
                    }
                });
            }else if ("英语".equals(newTeacher.getSubject())){
                gradeList=gradeList.stream().sorted(Comparator.comparing(CourseGrade::getEnglish).reversed()).collect(Collectors.toList());
                gradeList.forEach(courseGrade -> {
                    String studentNo = courseGrade.getStudentNo();
                    List<Student> collect = list.stream().filter(student -> student.getStudentNo().equals(studentNo)).collect(Collectors.toList());
                    if (!collect.isEmpty()){
                        System.out.println(collect.get(0) + "\t\t"+ "英语成绩=" + courseGrade.getEnglish());
                    }
                });
            }else {
                gradeList=gradeList.stream().sorted(Comparator.comparing(CourseGrade::getSports).reversed()).collect(Collectors.toList());
                gradeList=gradeList.stream().sorted(Comparator.comparing(CourseGrade::getEnglish).reversed()).collect(Collectors.toList());
                gradeList.forEach(courseGrade -> {
                    String studentNo = courseGrade.getStudentNo();
                    List<Student> collect = list.stream().filter(student -> student.getStudentNo().equals(studentNo)).collect(Collectors.toList());
                    if (!collect.isEmpty()){
                        System.out.println(collect.get(0) +"\t\t"+ "体育成绩=" + courseGrade.getSports());
                    }
                });
            }
        }
    }
    private static void selectStudentGrade(Teacher newTeacher) {
        // 查询出所有的学生
        List<Student> studentList = findAllStudent();
        List<CourseGrade> gradeList = findAllStudentGrade();
        List<Student> list = studentList.stream().filter(student ->  student.getStudentClass().equals(newTeacher.getTeacherClass())).collect(Collectors.toList());
        if (list.isEmpty()){
            System.out.println("你教学的班级里面没有学生");
        }else {
            list.forEach(student -> {
                List<CourseGrade> courseGradeList = gradeList.stream().filter(g -> g.getStudentNo().equals(student.getStudentNo())).collect(Collectors.toList());
                if (courseGradeList.isEmpty()){
                    System.out.println("该学生没有成绩");
                }else {
                     if ("数学".equals(newTeacher.getSubject())){
                         System.out.println("姓名:" + student.getName()+"   " + "班级:" + student.getStudentClass() +"   " + courseGradeList.get(0).getMath());
                     }else if ("英语".equals(newTeacher.getSubject())){
                         System.out.println("姓名:" + student.getName()+"   " + "班级:" + student.getStudentClass() +"   " + courseGradeList.get(0).getEnglish());
                     }else {
                         System.out.println("姓名:" + student.getName()+"   " + "班级:" + student.getStudentClass() +"   " + courseGradeList.get(0).getSports());
                     }
                }
            });
        }
    }
    private static void updateStudentInfo(Teacher newTeacher) {
        System.out.println("请输入你要修改学生的学号");
        String subjectName;
        Scanner studentNoScanner = new Scanner(System.in);
        String studentNo = studentNoScanner.next();
        // 查询出所有的学生
        List<Student> studentList = findAllStudent();
        List<CourseGrade> gradeList = findAllStudentGrade();
        List<CourseGrade> courseGradeList = gradeList.stream().filter(g -> g.getStudentNo().equals(studentNo)).collect(Collectors.toList());
        List<Student> list = studentList.stream().filter(student -> student.getStudentNo().equals(studentNo) && student.getStudentClass().equals(newTeacher.getTeacherClass())).collect(Collectors.toList());
        if (list.isEmpty()){
            System.out.println("你教学的班级里面没有该学号的学生");
        }else {
            Student student = list.get(0);
            if (courseGradeList.isEmpty()){
                System.out.println("名字:" +student.getName() + "\t"+ newTeacher.getSubject()+":" +"暂无成绩");
            }else {
                if ("数学".equals(newTeacher.getSubject())){
                    subjectName =courseGradeList.get(0).getMath();
                }else if ("英语".equals(newTeacher.getSubject())){
                    subjectName =courseGradeList.get(0).getEnglish();
                }else {
                    subjectName =courseGradeList.get(0).getSports();
                }
                System.out.println("名字:" +student.getName() + "\t\t"+ newTeacher.getSubject()+":" +subjectName);
                System.out.println("请输入您要修改的学生的"+newTeacher.getSubject()+"成绩为:");
                Scanner gradeScanner = new Scanner(System.in);
                String grade = gradeScanner.next();
                String finalFilePath = filePath + "course-grade.txt";
                if (Files.exists(Paths.get(finalFilePath))){
                    try {
                        Files.delete(Paths.get(finalFilePath));
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
                gradeList.forEach(g -> {
                    if (g.getStudentNo().equals(studentNo)){
                        if ("数学".equals(newTeacher.getSubject())){
                            g.setMath(grade);
                        }else if ("英语".equals(newTeacher.getSubject())){
                            g.setEnglish(grade);
                        }else {
                            g.setSports(grade);
                        }
                        writeCourseGrade(g);
                    }
                });
                System.out.println("修改成功!");
            }
        }
    }
    private static void getUserGrade(Student student, List<CourseGrade> gradeList) {

        while (true){
            System.out.println("请输入你要查询的单科成绩:  1.数学  2.英语  3.体育  4.退出" );
            boolean flag = true;
            Scanner selectScanner = new Scanner(System.in);
            String no = selectScanner.next();
            switch (no){
                case "1" :
                    System.out.println("你的数学成绩为: " + (!gradeList.isEmpty() ? gradeList.get(0).getMath(): "暂无成绩"));
                    break;
                case "2" :
                    System.out.println("你的英语成绩为: " + (!gradeList.isEmpty() ? gradeList.get(0).getEnglish(): "暂无成绩"));
                    break;
                case "3" :
                    System.out.println("你的体育成绩为: " + (!gradeList.isEmpty() ? gradeList.get(0).getSports(): "暂无成绩"));
                    break;
                case "4" :
                    System.out.println("退出成功");
                    flag = false;
                    break;
            }
            if (!flag){
                break;
            }
        }

    }
    private static List<Teacher> findAllTeacher() {
        String finalFilePath = filePath + "teacher.txt";
        if (!Files.exists(Paths.get(finalFilePath))) {
            try {
                Files.createFile(Paths.get(finalFilePath));
            } catch (IOException e) {
            }
        }
        List<Teacher> teachersList = new ArrayList<>();
        try (BufferedReader br = new BufferedReader(new FileReader(finalFilePath))) {
            String line;
            while ((line = br.readLine()) != null) {
                teachersList.add(parseTeacher(line));
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return teachersList;
    }

    private static List<Student> findAllStudent()  {
        String finalFilePath = filePath + "student-大数据一班.txt";
        if (!Files.exists(Paths.get(finalFilePath))) {
            try {
                Files.createFile(Paths.get(finalFilePath));
            } catch (IOException e) {
                
            }
        }
        String finalFilePath2 = filePath + "student-大数据二班.txt"; // 替换为你的文件路径
        exsitFile(finalFilePath2);
        List<Student> studentsList = new ArrayList<>();
        try (BufferedReader br = new BufferedReader(new FileReader(finalFilePath)); BufferedReader br2 = new BufferedReader(new FileReader(finalFilePath2))) {
            String line;
            while ((line = br.readLine()) != null) {
                studentsList.add(parseStudent(line));
            }
            String line2;
            while ((line2 = br2.readLine()) != null) {
                studentsList.add(parseStudent(line2));
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return studentsList;
    }

    private static void exsitFile(String finalFilePath2) {
        if (!Files.exists(Paths.get(finalFilePath2))) {
            try {
                Files.createFile(Paths.get(finalFilePath2));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }//
    }

    private static List<CourseGrade> findAllStudentGrade()  {
        String finalFilePath = filePath + "course-grade.txt";
        if (!Files.exists(Paths.get(finalFilePath))) {
            try {
                Files.createFile(Paths.get(finalFilePath));
            } catch (IOException ignored) {

            }
        }
        List<CourseGrade> studentsGradeList = new ArrayList<>();
        try (BufferedReader br = new BufferedReader(new FileReader(finalFilePath))) {
            String line;
            while ((line = br.readLine()) != null) {
                studentsGradeList.add(parseStudentGrade(line));
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return studentsGradeList;
    }

    private static Student parseStudent(String line) {
        String[] parts = line.split("\\s+");
        Student student = new Student();
        student.setStudentNo(parts[0].substring(3));
        student.setName(parts[1].substring(3));
        student.setAge(parts[2].substring(3));
        student.setSex(parts[3].substring(3));
        student.setSchool(parts[4].substring(3));
        student.setStudentClass(parts[5].substring(3));
        return student;
    }

    private static Teacher parseTeacher(String line) {
        String[] parts = line.split("\\s+");
        Teacher teacher = new Teacher();
        teacher.setTeacherNo(parts[0].substring(5));
        teacher.setName(parts[1].substring(3));
        teacher.setAge(parts[2].substring(3));
        teacher.setSex(parts[3].substring(3));
        teacher.setSchool(parts[4].substring(3));
        teacher.setTeacherClass(parts[5].substring(5));
        teacher.setSubject(parts[6].substring(5));
        return teacher;
    }
    private static CourseGrade parseStudentGrade(String line) {
        String[] parts = line.split("\\s+");
        CourseGrade courseGrade = new CourseGrade();
        courseGrade.setStudentNo(parts[0].substring(3));
        courseGrade.setMath(parts[1].substring(3));
        courseGrade.setEnglish(parts[2].substring(3));
        courseGrade.setSports(parts[3].substring(3));
        return courseGrade;
    }
}

